﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Net;
using System.Messaging;
using System.IO;
using System.Threading;


namespace BDM
{
    public partial class BDMForm : Form
    {
        #region Variables
        List<int> lPoorten = new List<int>();
        DataTable dtGrid = new DataTable();
        private Database db = new Database();
        private Message msg;
        public bool bAutoOpen = false;
        public bool bUpdateOpen = false;

        [DllImport("user32.dll")]
        private extern static bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
        #endregion

        public BDMForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            deleteOldFiles();
            setPosition();
            if (db.IsReachable() == true)
            {
                startPoorten();
                msg = new Message();
                runBGWorker();
                fillGrid();
                fillComboBox();
                tmrRefreshGrid.Start();
            }
            else
            {
                this.Close();
            }
        }

        private void deleteOldFiles()
        {
            SetData.RemoveOldFiles();
        }

        private void startPoorten()
        {
            sluitAllePoorten();
            List<string> list = GetData.GetAllPortIDs();
            for (int i = 0; i < list.Count; i++)
            {
                string pos = "";
                switch (list[i].ToString())
                {
                    case "1":
                        pos = (this.Location.X.ToString() + ";" + (this.Location.Y + this.Size.Height + 10).ToString()).ToString();
                        break;
                    case "2":
                        pos = ((this.Location.X + 175).ToString() + ";" + (this.Location.Y + this.Size.Height + 10).ToString()).ToString();
                        break;
                    case "3":
                        pos = ((this.Location.X + 354).ToString() + ";" + (this.Location.Y + this.Size.Height + 10).ToString()).ToString();
                        break;
                    case "4":
                        pos = ((this.Location.X + 527).ToString() + ";" + (this.Location.Y + this.Size.Height + 10).ToString()).ToString();
                        break;
                    case "5":
                        pos = (this.Location.X.ToString() + ";" + ((this.Location.Y + this.Size.Height + 20) + 100).ToString()).ToString();
                        break;
                    case "6":
                        pos = ((this.Location.X + 175).ToString() + ";" + ((this.Location.Y + this.Size.Height + 20) + 100).ToString()).ToString();
                        break;
                    case "7":
                        pos = ((this.Location.X + 354).ToString() + ";" + ((this.Location.Y + this.Size.Height + 20) + 100).ToString()).ToString();
                        break;
                    case "8":
                        pos = ((this.Location.X + 527).ToString() + ";" + ((this.Location.Y + this.Size.Height + 20) + 100).ToString()).ToString();
                        break;
                    default:
                        break;
                }
                Process prc = new Process();
                prc.StartInfo.FileName = Application.ExecutablePath;
                prc.StartInfo.Arguments = "poort " + list[i].ToString() + " " + pos;
                prc.Start();
                lPoorten.Add(prc.Id);
                if (prc.WaitForInputIdle(15000))
                {
                    SetWindowPos(prc.MainWindowHandle, Handle, Bottom, 0, 200, 200, 1);
                }
            }
        }

        private void fillComboBox()
        {
            List<string> list = GetData.GetAllCarIDs();
            cbFilter.Items.Add("Alles");
            for (int i = 0; i < list.Count; i++)
            {
                cbFilter.Items.Add(list[i].ToString());
            }
        }

        private void setPosition()
        {
            this.Location = new Point(((SystemInformation.PrimaryMonitorSize.Width - this.Size.Width) / 2), (((SystemInformation.PrimaryMonitorSize.Height - this.Size.Height) / 2) / 2));
        }

        private void sluitAllePoorten()
        {
            if (lPoorten.Count > 0)
            {
                foreach (int p in lPoorten)
                {
                    try
                    {
                        Process.GetProcessById(p).Kill();
                    }
                    catch { }
                }
                lPoorten.Clear();
            }
        }

        private void BDMForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            sluitAllePoorten();
        }

        private void btnOpenAuto_Click(object sender, EventArgs e)
        {
            if (bAutoOpen == false)
            {
                AutoForm frmAuto = new AutoForm(this);
                frmAuto.Show();
                bAutoOpen = true;
                frmAuto.Location = new Point((this.Location.X + this.Size.Width + 10), (this.Location.Y + ((this.Size.Height - frmAuto.Size.Height) / 2)));
            }
        }

        private void runBGWorker()
        {
            if (!bgwReceiver.IsBusy)
            {
                bgwReceiver.RunWorkerAsync();
            }
            else
            {
                Thread.Sleep(10);
                runBGWorker();
            }
        }

        private void bgwReceiver_DoWork(object sender, DoWorkEventArgs e)
        {
            receiveData();
        }

        private void fillGrid()
        {
            DataTable dt = new DataTable();
            if (cbFilter.SelectedIndex == -1)
            {
                dt = GetData.GetTransactions();
            }
            else if (cbFilter.SelectedIndex == 0)
            {
                dt = GetData.GetTransactions();
            }
            else
            {
                dt = GetData.GetFilteredTransactions(cbFilter.SelectedItem.ToString());
            }
            if (dt.Rows.Count != dtGrid.Rows.Count)
            {
                dtGrid = dt;
                dgPrijzen.DataSource = null;
                dgPrijzen.DataSource = dtGrid;
            }
        }

        private void receiveData()
        {
            string sText = msg.Receive("00");
            SetData.SetTransaction(sText[2].ToString() + sText[3].ToString() + sText[4].ToString() + sText[5].ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), sText[6].ToString() + sText[7].ToString() + sText[8].ToString() + sText[9].ToString());
        }

        private void bgwReceiver_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            runBGWorker();
        }

        private void tmrRefreshGrid_Tick(object sender, EventArgs e)
        {
            fillGrid();
        }

        private void cbSpits_CheckedChanged(object sender, EventArgs e)
        {
            DataTable dt = GetData.GetAllPortsAsDataTable();
            string[] ia = new string[dt.Rows.Count];
            for (int i = 0; i < ia.Length; i++)
            {
                if (dt.Rows[i][0].ToString().Length < 2)
                {
                    ia[i] = "0" + dt.Rows[i][0].ToString();
                }
                else
                {
                    ia[i] = dt.Rows[i][0].ToString();
                }
            }
            if (((CheckBox)sender).Checked == true)
            {
                msg.Send("03bs......", ia);
            }
            else
            {
                msg.Send("03bn......", ia);
            }
        }

        private void btnPrijsUpdate_Click(object sender, EventArgs e)
        {
            if (bUpdateOpen == false)
            {
                frmPrijsUpdate formPrijsUpdate = new frmPrijsUpdate(this);
                formPrijsUpdate.Show();
                bUpdateOpen = true;
                formPrijsUpdate.Location = new Point((this.Location.X - formPrijsUpdate.Size.Width - 10), (this.Location.Y + ((this.Size.Height - formPrijsUpdate.Size.Height) / 2)));
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            sluitAllePoorten();
            startPoorten();
        }

        private void cbFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            fillGrid();
        }

        private void pbAbout_Click(object sender, EventArgs e)
        {
            frmAbout formAbout = new frmAbout();
            formAbout.ShowDialog();
            formAbout.Dispose();
        }
    }
}
